<!-- 用户界面：健康咨询 -->
<template>
    <div class="MyContainer" style="padding:0px;">
        <div class="common-layout">
            <el-container style="justify-content: center;">
              <!-- 列表 -->
              <el-col :span="4">
                <div class="list-word">在线用户列表</div>
                  <div class="list-box">
                    <div class="list" :class="{'list_clicked' : chatUser === 'AI'}" @click="chooseUser({username:'AI',imgurl:'https://hkjtys.oss-cn-hangzhou.aliyuncs.com/%E6%9C%BA%E5%99%A8%E4%BA%BA.jpg'})">
                    <!-- AI头像 -->
                    <div class="head-img">
                      <img src="../../assets/img/robot.jpg" >
                    </div>
                    <!-- nameBox -->
                    <div class="nameBox">
                      <div class="name">
                        <span>问诊助手</span>
                        <el-icon style="margin-left: 10px; font-size: 16px; cursor: pointer"><ChatLineRound /></el-icon>
                        <span style="font-size: 12px;color: limegreen; margin-left: 5px" v-if="'AI' === chatUser">问诊中</span>
                      </div>
                      <div class="msgContent">
                        
                      </div>
                    </div>
                  </div>
                  <div class="list" 
                    v-for="user in users" 
                    :key="user.username" 
                    @click="chooseUser(user)"
                    :class="{'list_clicked' : user.username === chatUser}"
                    @contextmenu.prevent="closeCnt"
                  >
                    <!-- 头像 -->
                    <div class="head-img">
                      <el-avatar :src="user.imgurl"></el-avatar>
                    </div>
                    <!-- nameBox -->
                    <div class="nameBox">
                      <div class="name">
                        <span>{{ user.username }}</span>
                        <el-icon style="margin-left: 10px; font-size: 16px; cursor: pointer"><ChatLineRound /></el-icon>
                        <span style="font-size: 12px;color: limegreen; margin-left: 5px" v-if="user.username === chatUser">问诊中</span>
                      </div>
                      <div class="msgContent">
                        
                      </div>
                    </div>
                  </div>
                  <!-- 列表 -->
                    <div>
                      <ul id="menu" ref="rightClick" v-show="isShow">
                        <li @click="closeList">
                          结束问诊
                        </li>
                      </ul>
                    </div>
                </div>
              </el-col>
              <!-- 聊天框 -->
              <el-col :span="12">
                <div class="right-part">

                  <div class="dialog">
                    <!-- 标题 -->
                    <div v-if="chatUser!='AI'" class="title">
                      {{ chatUser }}
                    </div>
                    <div v-else class="title">问诊助手</div>
                    <!-- 消息列表 -->
                    <div class="msg-list" >
                      <div class="chat-box">
                        <ul>
                          <li v-for="(item,idx) in new_content" :key="idx">
                            <div v-if="item.id === chatUser" v-html="item.content"></div>
                          </li>
                        </ul>
                      </div>
                    </div>
                    <!-- 发送框 -->
                    <div class="send-box">
                      <el-input
                        class="inputBox"
                        v-model="text"
                        maxlength="60"
                        placeholder="回复一下吧"
                        show-word-limit
                        type="textarea"
                        :rows="5"
                      />
                      <div class="send-btn">
                        <el-button style="width: 80px; margin-right: 10px;" type="primary" @click="send" @disabled="click">发送</el-button>
                      </div>
                    </div>
                  </div>
                </div>
              </el-col>
            </el-container>
        </div>   
    </div>
</template>
  
<script>
import { reactive, ref } from 'vue'
import { ElMessage,ElMessageBox } from 'element-plus';
import { closeCnt,getBookedDoc } from '../../api/manager.js';
import { useGlobleStore } from '../../store/globle';

let socket;
export default {
  data() {
    return {
      circleUrl: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      user: {},
      isCollapse: false,
      users: [],
      accept:[],
      chatUser: '',
      chatImg:'',
      text: "",
      messages: [],
      new_content:[],
      userDialog:new Set(),
      isShow:false,
      globle:useGlobleStore(),
      click:false,
      count:0
    }
  },
  created() {
    this.init()
  },
  mounted(){
    document.addEventListener('click',e=>{
      this.isShow = false
    })
  },
  methods: {
    send() {
      if (!this.chatUser) {
        this.$message({type: 'warning', message: "请选择聊天对象"})
        return;
      }
      if (!this.text) {
        this.$message({type: 'warning', message: "请输入内容"})
      } else {
        if (typeof (WebSocket) == "undefined") {
          //MessageBox
          ElMessage({
            message: '您的浏览器不支持WebSocket',
            type: 'warning',
          })
        } else if(this.chatUser === "AI"){
          this.chat()
        }
        else{
          // 组装待发送的消息 json
          // {"from": "zhang", "to": "admin", "text": "聊天文本"}
          let message = {from: this.user.username, to: this.chatUser, text: this.text}
          socket.send(JSON.stringify(message));  // 将组装好的json发送给服务端，由服务端进行转发
          this.messages.push(/*{user: this.user.username, text: this.text}*/message)
          // 构建消息内容，本人消息
          this.createContent(null, this.user.username, this.text)
          this.text = '';
        }
      }
    },
    chat(){
      this.click=true;
      let url = 'http://47.113.217.179:8080/openai/request?question=' + this.text;
      this.createContent(null,this.user.username,this.text)
      this.text = '';

      var ai_text=''
      let es = new EventSource(url);
      es.addEventListener('message', event => {
        //console.log(event.data);
        this.count++;
        if (this.count > 2) {
          if (event.data.toString() === "Answer Done!") {
            es.close();
            //回答结束
            this.count = 0;
            this.click = false;
            this.createContent(this.chatUser,null,ai_text)
            ai_text = ''
          } else {
            ai_text += event.data;
          }
        }
      });
    },
    createContent(remoteUser, nowUser, text) {  // 这个方法是用来将 json的聊天消息数据转换成 html的。
      let html
      // 当前用户消息
      if (nowUser) { // nowUser 表示是否显示当前用户发送的聊天消息，绿色气泡
        html = "<div class=\"" + this.chatUser+ " el-row\" style=\"padding: 5px 0\">\n" +
            "  <div class=\"el-col el-col-22\" style=\"text-align: right; padding-right: 10px\">\n" +
            "    <div style=\"color:white;border-radius:10px;font-family:sans-serif;padding:10px;width:auto;max-width:300px;display:inline-block !important;display:inline;background-color: deepskyblue;\">" + text + "</div>\n" +
            "  </div>\n" +
            "  <div class=\"el-col el-col-2\">\n" +
            "  <span class=\"el-avatar el-avatar--circle\" style=\"height: 40px; width: 40px; line-height: 40px;\">\n" +
            "    <img src=\""+ this.globle.getAvater() + "\" style=\"object-fit: cover;\">\n" +
            "  </span>\n" +
            "  </div>\n" +
            "</div>";
      } else if (remoteUser) {   // remoteUser表示远程用户聊天消息，蓝色的气泡
        html = "<div class=\"" + this.chatUser+ " el-row\" style=\"padding: 5px 0\">\n" +
            "  <div class=\"el-col el-col-2\" style=\"text-align: right\">\n" +
            "  <span class=\"el-avatar el-avatar--circle\" style=\"height: 40px; width: 40px; line-height: 40px;\">\n" +
            "    <img src=\"" + this.chatImg + "\">\n" +
            "  </span>\n" +
            "  </div>\n" +
            "  <div class=\"el-col el-col-22\" style=\"text-align: left; padding-left: 10px\">\n" +
            "    <div style=\"color:white;border-radius:10px;font-family:sans-serif;padding:10px;width:auto;max-width:300px;display:inline-block !important;display:inline;background-color: rgb(109, 194, 109);\">" + text + "</div>\n" +
            "  </div>\n" +
            "</div>";
      }
      this.new_content.push({
        id:this.chatUser,
        content:html
      })
    },
    setItemUnDisplay(id){
      var div = document.getElementsByClassName(id)
      for(var i = 0;i < div.length;i++){
        div[i].style.display="none"
      }
    },
    setItemDisplay(id){
      var div = document.getElementsByClassName(id)
      for(var i = 0;i < div.length;i++){
        div[i].style.display="flex"
      }
    },
    chooseUser(user){
      let menu = this.$refs.rightClick  
      menu.style.display = "none";
      //改变当前聊天对象
      this.chatUser = user.username
      this.chatImg = user.imgurl
      console.log("choose:",this.chatUser)
      if(this.chatUser != 'AI')this.click = false
      //将 chatUser 加入集合中
      this.userDialog.add(this.chatUser)
      //遍历 userDialog，将非 chatUser 的对话设置为不可见
      this.userDialog.forEach( dia =>{
        //若是非当前聊天对象，则设置不可见
        if(dia !== this.chatUser){
          this.setItemUnDisplay(dia)
        }else{//否则可见
          this.setItemDisplay(dia)
        }
      })
    },
    hasAccepyed(username){
      for(var i = 0;i < this.accept.length;i++){
        if(this.accept[i].username == username){
          this.users.push(this.accept[i])
          break;
        }
      }
    },
    closeCnt(){
      let menu = this.$refs.rightClick
      
      this.isShow = true
      var evt = window.event;
      var clientWidth = document.documentElement.clientWidth || document.body.clientWidth ;
      var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
     
      var clientHeight = document.documentElement.clientHeight || document.body.clientHeight ;
      var scrollTop = document.documentElement.scrollTop || document.body.scrollTop ;
      
      var pos = document.getElementsByClassName('content-box')[0]

      //给left和top分别赋值为鼠标的位置；
      menu.style.left = evt.pageX - pos.offsetLeft +"px";
      menu.style.top = evt.pageY - pos.offsetTop +"px";
      //console.log("left:",menu.style.left,"top:",menu.style.top)
        //如果鼠标右边放不下菜单，就把left的值的改了
      if(evt.pageX + 100 > clientWidth + scrollLeft){//菜单应该在鼠标左边；
        var left1 = evt.pageX-100;
        menu.style.left = left1+"px";
      }
        //如果鼠标下边放不下菜单，就把top的值的改了
      if(evt.pageY+100>clientHeight+scrollTop){
        var top1 = (evt.pageY-100);
        menu.style.top = top1+"px";
      }
      menu.style.display = "block";
    },
    closeList(){
      let that = this
      //MessageBox
      ElMessageBox.confirm(
        '确定要关闭会话吗？关闭后消息记录会丢失。',
        'Warning',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
      .then(() => {
        //console.log('name',that.chatUser)
        closeCnt(that.chatUser).then(res => {
          ElMessage({
            type: 'success',
            message: '成功！',
          })
          //删除列表
          for(var i = 0;i < this.users.length;i++)
            if(that.users[i].username == that.chatUser)that.users.splice(i,1)
        })
        .catch(err=>{
          ElMessage({
            type: 'success',
            message: '失败',
          })
        })
        ElMessage({
          type: 'success',
          message: '成功！',
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消',
        })
      })
    },
    init() {
      let _this = this;
      //获取已经接受就诊的病人
      getBookedDoc().then(res=>{
        console.log("res:",res)
        if(res.data != undefined){
          for(var i = 0;i < res.data.length;i++){
            _this.accept.push({
              username:res.data[i].docName,
              imgurl:res.data[i].avatar
            })
          }
        }
      }).catch(err=>{
        console.log("err:",err)
      })
      //初始化
      this.user = sessionStorage.getItem("globle") ? JSON.parse(sessionStorage.getItem("globle")) : {}
      let username = this.user.username;    
      if (typeof (WebSocket) == "undefined") {
        ElMessage({
          message: '您的浏览器不支持WebSocket',
          type: 'warning',
        })
      } else {
        let socketUrl = "ws://47.113.217.179:8080/websocket/" + username;
        if (socket != null) {
          socket.close();
          socket = null;
        }  
        // 开启一个websocket服务
        socket = new WebSocket(socketUrl);
        //打开事件
        socket.onopen = function () {
          //console.log("websocket已打开");
          ElMessage({
            message: 'WebSocket已打开',
            type: 'success',
          })
        };

        //浏览器端收消息，获得从服务端发送过来的文本消息
        socket.onmessage = function (msg) {
          let data = JSON.parse(msg.data)  // 对收到的json数据进行解析，类似这样的：{"users": [{"username": "zhang"},{ "username": "admin"}]}
          if (data.users) {  // 获取在线人员信息
            _this.users = []
            data.users.forEach(user => _this.hasAccepyed(user.username))
            //_this.users = data.users.filter(user => (user.username !== username) && (_this.hasAccepyed(user.username))) //获取当前连接的所有用户信息，并且排除自身，自己不会出现在自己的聊天列表里
          } 
          else {
            // 如果 [服务器端发送] 过来的json数据 不包含 users 这个key，那么发送过来的就是聊天文本json数据
            // {"from": "zhang", "text": "hello"}
            if (data.from === _this.chatUser) {
              let message = {from: _this.chatUser, to: _this.user.username, text: data.text}
              _this.messages.push(message)
              // 构建消息内容
              _this.createContent(data.from, null, data.text)
            }
          }
        };        
        //关闭事件
        socket.onclose = function () {
          ElMessage({
            message: 'Web连接已关闭',
            type: 'success',
          })
        };
        //发生了错误事件
        socket.onerror = function () {
          ElMessage.error('websocket发生了错误')
        }
      }
    }
  }
}

</script>       

<style scoped>
#menu{
  display: flex;
  list-style: none;
  margin: 0px;
  padding: 0px;
  position: absolute;
  width: 100px;
  background-color: #a9d0ea;
  z-index: 3;
  justify-content: center;
  border: 0.5px solid #79a4c1;
  border-radius: 5px;
}

#menu:hover{
  background-color: #83d19e;
  box-shadow: 3px 3px 3px #c2cbc5;
}
 
#menu li{
  margin: 0px;
  padding: 0px;
}

.common-layout{
  /* background: url(../assets/img/chat-bg.jpeg); */
  border-radius: 5px ;
  background-image: url(../../assets/img/1.jpg);
  background-repeat: no-repeat;
  background-position: 10%;
  /* margin-bottom: 20px; */
}
.right-part{
  -webkit-box-flex: 1;
  flex: 1;
}
.dialog{
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  flex-direction: column;
  -webkit-box-align: stretch;
  align-items: stretch;
  height: 100%;
}
.title{
  height: 36px;
  flex-shrink: 0;
  display: flex;
  -webkit-box-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  align-items: center;
  border-bottom: 1px solid #e9eaec;
  position: relative;
  text-align: center;
  color: #333;
  margin-top: 35px;
  background-color: #f4f5f6;
  border-radius: 0 8px 0 0 ;
}
.msg-list{
  -webkit-box-flex: 1;
  flex: 1;
  position: relative;
  overflow-x: hidden;
  overflow-y: hidden;
  background-color:#f4f5f7 ;
}
.msg-list-content{
  height: 428.5px;
  overflow: auto;
}
.send-box{
  height: 161px;
  border-top: 1px solid #d8d8d8;
  border-bottom-right-radius: 4px;
  flex-shrink: 0;
  /* padding: 0 16px; */
  position: relative;
  z-index: 2;
  background-color: #fefbfb;
  display: flex;
  flex-direction: column;
  border-bottom: 0.5px solid #948787;
}
.space{
  padding :0px;
  width: -webkit-fill-available;
}

.list-box{
  /* border: 1px solid #1b9bbf; */
  /* padding: 3px; */
  /* margin-top: 20px; */
  height: 590px;
  background-color: #f4f5f6;
  border-right: 0.5px solid #948787;
  border-radius: 0 0 0 8px;
  border-bottom: 0.5px solid #948787;
  margin-bottom: 20px;
}

.list-word{
  /* border: 1px solid #000; */
  margin-top: 20px;
  /* margin-bottom: 2px; */
  background-color: #f4f5f7;
  /* border-radius: 5px; */
  line-height: 35px;
  height: 35.6px;
  display: flex;
  align-items: center;
  font-size:14px;
  padding-left: 5px;
  border-right: 0.5px solid #948787;
  border-bottom: 0.5px solid #b4aaaa;
  border-radius: 8px 0 0 0;
  margin-top: 35px;
}

.list{
  /* border-radius: 5px; */
  /* border: 1px solid #1b9bbf; */
  height: 80px;
  /* border-top: 1px solid #000; */
  /* margin-bottom: 3px; */
  background-color: #9ecae8;
  display: flex;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  flex-direction: row;
  padding: 15px 20px;
  position: relative;
  overflow: hidden;
  cursor: pointer;
}

.list:hover{
  background-color: aliceblue;
}

.list_clicked{
  background-color: aliceblue;
}

.nameBox{
  font-size: 14px;
  margin-left: 10px;
}

.name{
  font-size: 15px;
}

.head-img{
  width: 50px;
  height: 50px;
}

.msgContent{
  margin-top: 3px;
}

.inputBox{
  width: 100%;
}

.send-btn{
  display: flex;
  height: 45px;
  justify-content: flex-end;
  align-items: center;
}

.chat-box{
  height: 428.5px;
  /* border:1px solid #000 ; */
  /* border-radius: 3px; */
  overflow: auto;
  overflow-x: hidden;
  background-color: aliceblue;
}

.box-card1{
  padding: 0px;
  height: 520px;
  width: auto;
  /* background-image: url(../../assets/img/chat-bg1.jpg); */
  background: linear-gradient(#a6bdf0,#86a8e7,#9faeed); 
}

.box-card2{
  height: 100px;
  /* margin-left: 20px; */
  background: linear-gradient(#a6bdf0,#86a8e7,#9faeed); 
}

.sendBtn{
  margin-top: 2.5px ;
  margin-left: 10px;
}
.tip {
  color: white;
  text-align: center;
  border-radius: 10px;
  font-family: sans-serif;
  padding: 10px;
  width:auto;
  display:inline-block !important;
  display:inline;
}

.right {
  background-color: deepskyblue;
}

.left {
  background-color: rgb(109, 194, 109);
}
</style>

  
  